module API::V3
  class Apps < Grape::API
    resource :apps do
      post :watch do
        watch = Watching.new params[:watching]
        if watch.save
          present :status, true
        else
          bad_request!("watching")
        end
      end

      params do
        requires :current_version, type: String
        optional :branch, type: String, default: 'public'
      end
      get :version do
        app_type = ['ios', 'android'].include?(params[:app_type].to_s.downcase) ? params[:app_type].to_s.downcase : 'ios'
        branch = ['public', 'private'].include?(params[:branch].to_s.downcase) ? params[:branch].to_s.downcase : 'public'
        name = 'ymtv_' + app_type
        client_appversion = AppVersion.where(
          version: params[:current_version], 
          release: true, 
          name: name,
          branch: branch
        ).first
        if client_appversion == nil
          present :result, false
          present :message, 'invalid client version'
          present :error_code, 1
        else
          present :result, true
          latest_appversion = client_appversion
          enforce = false
          AppVersion.where(release: true, name: name).each do |appversion|
            latest_appversion = appversion if appversion.is_greater?(latest_appversion)
            enforce ||= appversion.enforce if appversion.is_greater?(client_appversion)
          end

          if latest_appversion == client_appversion
            present :is_latest, true
          else
            present :is_latest, false
            present :release_version, latest_appversion.version
            present :changelog, latest_appversion.note
            if app_type == 'ios'
              link = latest_appversion.itunes_url
            else
              link = request.scheme + '://' + request.host_with_port + latest_appversion.file.url.to_s
            end
            present :link, link
            present :enforce, enforce
          end
        end
      end
    end
  end
end